/**
 * Copyright (C), 2015-2019, XXX有限公司
 * FileName: GoldenAuthenticationSucessHandler
 * Author:   zhouheng
 * Date:     2019/6/7 17:08
 * Description: 登陆成功处理器
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.zhouh.golden.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhouh.golden.common.constants.GoldenConstant;
import com.zhouh.golden.common.domain.ResponseBo;
import com.zhouh.golden.security.domain.GoldenUserDetails;
import com.zhouh.golden.security.domain.LoginType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.security.web.authentication.session.ConcurrentSessionControlAuthenticationStrategy;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 〈一句话功能简述〉<br> 
 * 〈登陆成功处理器〉
 *
 * @author zhouheng
 * @create 2019/6/7
 * @since 1.0.0
 */
@Slf4j
public class GoldenAuthenticationSucessHandler implements AuthenticationSuccessHandler {
    private SessionRegistry sessionRegistry;
    private ObjectMapper mapper = new ObjectMapper();

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        log.info("登陆成功~");
        WebAuthenticationDetails details = (WebAuthenticationDetails) authentication.getDetails();
        String remoteAddress = details.getRemoteAddress();

        LoginType loginType = LoginType.normal;
        Object principal = authentication.getPrincipal();
        if (principal instanceof GoldenUserDetails) {
            GoldenUserDetails userDetails = (GoldenUserDetails) principal;
            userDetails.setRemoteAddress(remoteAddress);
            loginType = userDetails.getLoginType();
        }

        response.setContentType(GoldenConstant.JSON_UTF8);
        response.getWriter().write(mapper.writeValueAsString(ResponseBo.ok()));
    }

    public void setSessionRegistry(SessionRegistry sessionRegistry) {
        this.sessionRegistry = sessionRegistry;
    }
}